package query;


import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import document.InvertedIndex;



public class NotOperand implements Query
{

	@Override
	public int getOrder() {
		return 1;
	}

	@Override
	public List<Integer> getResult() {
		return queryResult;
	}

	@Override
	public List<Query> getSubQueries() {
		List<Query>  result = new LinkedList<Query>();
		result.add(negatedQuery);
		return result;
	}

	@Override
	public void process(InvertedIndex i) 
	{
		queryResult = new LinkedList<Integer>();
		if(!negatedQuery.isNeutralQuery())
		{
			negatedQuery.process(i);
			ListIterator<Integer> it = negatedQuery.getResult().listIterator();
			
			int next = -1;
			for(int j=0; j<i.getNumberOfDocuments(); j++)
			{	
				if(next < j)
				{
					boolean isSmaller = true;
					while(it.hasNext() && isSmaller)
					{
						next = it.next();
						if(next >= j)
						{
							isSmaller = false;
						}
					}
				}
				if(next > j || !it.hasNext())
				{
					queryResult.add(j);
				}
			}
		}	
	}

	@Override
	public void putLeftOperand(Query q) 
	{
		// do nothing	
	}

	@Override
	public void putRightOperand(Query q) 
	{
		negatedQuery = q;
	}
	
	
	@Override
	public String getName() {
		
		return "";
	}
	
	private Query negatedQuery;
	private List<Integer> queryResult;
	@Override
	public boolean isNeutralQuery() 
	{
		return negatedQuery.isNeutralQuery();
	}

	@Override
	public boolean isHomogenious() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Query rebuildOptimal(InvertedIndex i) 
	{
		return this;
	}

	@Override
	public Query rebuildWorst(InvertedIndex i) {
		return this;
	}

	@Override
	public List<Term> getLeaves() {
		return negatedQuery.getLeaves();
	}
}
